package com.ruoyi.common.utils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <pre>
 *    description
 * </pre>
 *
 * @author zhangli
 * @version 1.0
 * @since 2025/8/22
 */
@Component
public class RedisLock {

    private final RedisTemplate<Object, Object> redisTemplate;

    public RedisLock(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    // 锁的前缀（避免键冲突）
    private static final String LOCK_PREFIX = "ry_lock:";

    // 获取锁
    public boolean tryLock(String lockKey,String clientId, long timeout, TimeUnit unit) {
        long expireTime = unit.toMillis(timeout);
        // 使用 SET NX PX 命令获取锁
        Boolean result = redisTemplate.opsForValue().setIfAbsent(
                LOCK_PREFIX + lockKey,
                clientId,
                expireTime,
                TimeUnit.MILLISECONDS
        );
        return result != null && result;
    }

    // 释放锁
    public boolean releaseLock(String lockKey, String clientId) {
        String script = "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
        Long result = redisTemplate.execute(
                redisScript,
                Collections.singletonList(LOCK_PREFIX + lockKey),
                clientId
        );
        return result != null && result > 0;
    }

}
